<template>
  <div class="chart-container">
     <div class="chart-header">
       <h3 class="chart-title">{{ title }}</h3>
       <div class="chart-controls">
         <div class="time-range-selector">
           <el-date-picker
             v-model="dateRange"
             type="daterange"
             range-separator="至"
             start-placeholder="开始日期"
             end-placeholder="结束日期"
             value-format="YYYY-MM-DD"
             size="small"
           />
           <el-select v-model="selectedFrequency" size="small" class="frequency-select">
             <el-option label="全部" value="all" />
             <el-option label="月度" value="monthly" />
             <el-option label="周度" value="weekly" />
             <el-option label="日度" value="daily" />
           </el-select>
         </div>
         <el-checkbox v-model="showExtremes">显示最值</el-checkbox>
       </div>
     </div>
    <div class="chart-content">
      <v-chart 
        ref="chartRef"
        :option="chartOption" 
        :style="{ height: height + 'px' }" 
        class="chart" 
        :autoresize="true"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import type { ChartSeries, EChartsOption } from '../types'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
])

interface Props {
  title: string
  series: ChartSeries[]
  height?: number
  chartType?: 'line' | 'bar'
  yAxisRange?: [number, number]
  showDataZoom?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  height: 300,
  chartType: 'line',
  yAxisRange: undefined,
  showDataZoom: true
})

const dateRange = ref<[string, string]>(['2007-07-02', '2023-06-30'])
const selectedFrequency = ref('all')
const showExtremes = ref(false)

// ECharts 实例引用
const chartRef = ref()

// 自动调整大小
const handleResize = () => {
  if (chartRef.value) {
    chartRef.value.resize()
  }
}

// 监听窗口大小变化
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const chartOption = computed<EChartsOption>(() => {
  const [startDate, endDate] = dateRange.value
  
  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: props.series.map(s => s.name),
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.series[0]?.data.map(d => d.date) || []
    },
    yAxis: {
      type: 'value',
      ...(props.yAxisRange && {
        min: props.yAxisRange[0],
        max: props.yAxisRange[1]
      })
    },
    series: props.series.map(series => ({
      name: series.name,
      type: props.chartType,
      data: series.data.map(d => d.value),
      smooth: true,
      lineStyle: {
        color: series.color
      },
      itemStyle: {
        color: series.color
      }
    }))
  }

  if (props.showDataZoom) {
    option.dataZoom = [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ]
  }

  return option
})

// 监听时间范围变化
watch([dateRange, selectedFrequency, showExtremes], () => {
  // 这里可以触发数据重新加载
  console.log('Chart controls changed:', {
    timeRange: dateRange.value,
    frequency: selectedFrequency.value,
    showExtremes: showExtremes.value
  })
})
</script>

<style scoped>
.chart-container {
  @apply bg-white rounded-lg shadow-sm p-4;
}

.chart-header {
  @apply flex justify-between items-center mb-4;
}

.chart-title {
  @apply text-lg font-semibold text-gray-800;
}

.chart-controls {
  @apply flex items-center space-x-4;
}

.time-range-selector {
  @apply flex space-x-2;
}

.time-select,
.frequency-select {
  @apply px-3 py-1 border border-gray-300 rounded text-sm;
}

.extremes-checkbox {
  @apply flex items-center text-sm text-gray-600;
}

.chart-content {
  @apply w-full;
}

.chart {
  @apply w-full;
}
</style>
